package com.qriver.session.interceptor;

import com.qriver.session.common.SsoConstant;
import com.qriver.session.redis.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Token 拦截器
 */
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 返回 true，表示验证通过，false，表示验证失败
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader(SsoConstant.HEADER_USER_ID);
        String userToken = request.getHeader(SsoConstant.HEADER_USER_TOKEN);

        if(!StringUtils.isEmpty(userId) && !StringUtils.isEmpty(userToken) ){
            //获取用户在redis中对应的token
            String redisToken = redisOperator.get(SsoConstant.REDIS_USER_TOKEN + ":" + userId);
            if(StringUtils.isEmpty(redisToken)){
                returnErrorResponse(response, "请登录...");
                return false;
            }else{
                if(!userToken.equals(redisToken)){
                    returnErrorResponse(response, "用户Token失效，请重新登录...");
                    return false;
                }
            }
        }else{
            returnErrorResponse(response, "请登录...");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public void returnErrorResponse(HttpServletResponse response,
                                    String result) {
        OutputStream out = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(result.getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
